﻿using Prism.DryIoc;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using YiDunXray.Common;
using YiDunXray.Services;
using YiDunXray.Views;

namespace YiDunXray
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        public App()
        {
            LoggerHelper.WriteLog("程序启动...", LogType.Info);
            // 1.程序启动入口事件
            Startup += Application_Startup;
            // 2. UI线程未捕获异常事件
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            // 3. 异步Task任务中未捕获异常
            TaskScheduler.UnobservedTaskException += Task_UnObservedTaskException;
            // 4. 整个程序域未捕获异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void Task_UnObservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LoggerHelper.WriteLog("UI未捕获异常事件中: " + e.Exception.Message, LogType.Exception);
            DialogParameters parameters = new DialogParameters()
            {
                {"Title","UI未捕获异常提示" },
                {"Exception",e.Exception }
            };
            e.Handled = true;
            DialogProvider.ShowDialog(nameof(ExceptionDialog), parameters);
        }

        private void ShowSplashScreen()
        {
            var splashScreen = new SplashScreen("Assets/Images/startFlash.png");
            // 是否自动关闭
            splashScreen.Show(true);
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // 1. 检测程序是否已经启动,如果已经启动就通知旧程序激活
            SingleInstanceManager.SingleInstanceCheck();
            // 2. 显示启动画面
            ShowSplashScreen();
            // 3. GC垃圾回收,优化WPF内存占用过大问题
            WpfHelper wpfHelper = new WpfHelper();
            wpfHelper.GcTaskStart(500);
        }

        protected override Window CreateShell()
        {
            return Container.Resolve<MainView>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // 3. 没有构造方法的类中的依赖注入,通过静态方法的方式来进行依赖注入.比如提供弹窗的类
            DialogPrivider.SetDialogService(Container.Resolve<IDialogService>());
        }
    }
}
